<?php

class User extends FrontEnd_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('User_m');
        $this->load->model('Admin_user_m');
        $this->load->model('Admin_m');
        $this->load->library('email');
        $this->load->helper('cookie');
    }

    function index() {
        is_user();
        $this->_data['hmenu_index'] = 0;
        $this->display_view('users/index');
    }

    function login() {
        $this->_data['hmenu_index'] = 0;
        $utc = now();
        //validate login form//
        if ($this->input->post('submit')) {
            $formVal = array(array(
            'field' => 'email',
            'Label' => 'Email',
            'rules' => 'required|valid_email|callback__active_check'
            ),
            array(
            'field' => 'pass',
            'Label' => lang('password'),
            'rules' => 'required'
            )
            );
            $this->form_validation->set_rules($formVal);
            //------------------//
            if ($this->form_validation->run() === TRUE) {
                $email = $this->input->post('email');
                $password = md5($this->input->post('pass'));
                $query = $this->User_m->get_user($email, $password);
                if ($query->num_rows > 0) {
                    $login_user = $query->row();
                    $data = array('last_login' => $utc);
                    $this->User_m->change_login_time($data, $login_user->id);
                    $this->session->set_userdata('client_display_name', $login_user->display_name);
                    $this->session->set_userdata('client_group_id', $login_user->group_id);
                    $this->session->set_userdata('client_id', $login_user->id);
                    if ($this->input->post('remember') == 1) {
                        setcookie("email_belli_client", $email, time() + 2592000);
                        setcookie("pass_belli_client", $this->input->post('pass'), time() + 2592000);
                    }
                    $desination = $this->session->userdata('current_url') != NULL ? $this->session->userdata('current_url') : site_url('admin_content');
                    redirect($desination);
                } else {
                    $this->session->set_flashdata('error', 'Wrong email or password, Please try again');
                    redirect('user/login');
                }
            } else {
                $this->display_view('users/login');
            }
        } else {
            $this->display_view('users/login');
        }
    }
    function login_order(){
        $this->_data['hmenu_index'] = 0;
        $this->session->set_userdata('current_url', current_url());
        if($this->input->post('btnLogin')){
            $formVal = array(array(
            'field' => 'login_email',
            'Label' => 'email',
            'rules' => 'required|valid_email|callback__active_check'
            ),
            array(
            'field' => 'password',
            'Label' => lang('password'),
            'rules' => 'required'
            )
            );
            $this->form_validation->set_rules($formVal);
            if($this->form_validation->run()){
                $email = $this->input->post('login_email');
                $password = $this->input->post('password');
                if($this->process_login($email,$password)){
                    redirect('order/step/1');
                } else{
                    $this->session->set_flashdata('error',lang('invalid_login'));
                    redirect('order/step/1');
                }    
            }else{
                $this->display_view('order/login_register');    
            }        
        } else{
            $this->display_view('order/login_register');
        }    
    }
    function process_login($email, $pass) {
        $utc = now();
        $password = md5($pass);
        $query = $this->User_m->get_user($email, $password);
        if ($query->num_rows > 0) {
            $login_user = $query->row();
            $data = array('last_login' => $utc);
            $this->User_m->change_login_time($data, $login_user->id);
            $this->session->set_userdata('client_display_name', $login_user->display_name);
            $this->session->set_userdata('client_group_id', $login_user->group_id);
            $this->session->set_userdata('client_id', $login_user->id);
            if ($this->input->post('remember') == 1) {
                setcookie("email_belli_client", $email, time() + 2592000);
                setcookie("pass_belli_client", $this->input->post('pass'), time() + 2592000);
            }
            return true;
        } else{
            return false;
        }
    }

    function logout() {
        $this->session->unset_userdata('client_id');
        $desination = $this->session->userdata('current_url') != NULL ? $this->session->userdata('current_url') : site_url('home');
        redirect($desination);
    }

    /**
    * Method to register a new user
    * @access public
    * @return void
    */
    function register() {
        $this->_data['hmenu_index'] = 0;
        $this->session->set_userdata('current_url', current_url());
        /* Captcha */
        //$this->load->view('accueil/register_success');
        $expiration_period = time() - 1800;
        $this->db->query("DELETE FROM captcha WHERE captcha_time < " . $expiration_period);
        $this->load->helper('captcha');
        $vals = array(
        'word' => strtoupper(random_string('alnum', 6)),
        'img_path' => './assets/captcha/',
        'img_url' => base_url() . 'assets/captcha/',
        'font_path' => base_url() . 'system/fonts/texb.ttf',
        'img_width' => '150',
        'img_height' => 32,
        'expiration' => 300
        );

        $cap = create_captcha($vals);

        $cap_save = array(
        'captcha_id' => '',
        'captcha_time' => $cap['time'],
        'ip_address' => $this->input->ip_address(),
        'word' => $cap['word']
        );
        $query = $this->db->insert_string('captcha', $cap_save);
        $this->db->query($query);
        $this->_data['captcha_img'] = $cap['image'];
        /* End of captcha */

        $back = $this->input->post('back');
        $active =0;
        if($back!=null){
            $active = 1;
        }
        if ($this->input->post('register')) {
            //Validation rules
            $validation = array(
            array(
            'field' => 'first_name',
            'label' => lang('first_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'last_name',
            'label' => lang('last_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'password',
            'label' => lang('password'),
            'rules' => 'required|min_length[6]|max_length[20]'
            ),
            array(
            'field' => 'confirm_pass',
            'label' => lang('confirm_pass'),
            'rules' => 'required|matches[password]'
            ),
            array(
            'field' => 'email',
            'label' => lang('email'),
            'rules' => 'required|valid_email|callback__email_check|xss_clean'
            ),
            array(
            'field' => 'confirm_email',
            'label' => lang('confirm_email'),
            'rules' => 'required|valid_email|matches[email]|xss_clean'
            ),
            array(
            'field' => 'display_name',
            'label' => lang('display_name'),
            'rules' => 'required|alphanumeric|maxlength[50]'
            ),
            array(
            'field' => 'address',
            'label' => lang('address'),
            'rules' => 'required|alphanumeric|maxlength[50]'
            ),
            array(
            'field' => 'captcha',
            'Label' => 'Picture letters',
            'rules' => 'required|max_length[6]|callback_is_correct_captcha'
            )
            );

            // Set the validation rules
            $this->form_validation->set_rules($validation);

            $email = $this->input->post('email');
            $password = $this->input->post('password');
            $date_of_birth = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . date('H:i', time());
            $dob_long = human_to_unix($date_of_birth);
            $user_data_array = array(
            'first_name' => $this->input->post('first_name'),
            'last_name' => $this->input->post('last_name'),
            'display_name' => $this->input->post('display_name'),
            'dob' => $dob_long,
            'gender' => $this->input->post('gender'),
            'phone' => $this->input->post('phone'),
            'mobile' => $this->input->post('mobile'),
            'address' => $this->input->post('address')
            );
            if ($this->form_validation->run()) {
                /* Insert data into users table */
                if ($this->User_m->register($password, $email, $user_data_array,$active)) {
                    $this->session->set_flashdata('success', lang('register') . ' ' . lang('success') . ' ' . lang('note'));
                    if($back!=null){
                        if($this->process_login($email, $password)){
                            redirect($back);
                        }
                    }
                    redirect('user/success');
                }
                // Can't create the user, show why
                else {
                    $this->_data['error_string'] = lang('register') . ' ' . lang('fail');
                }
            } else {
                $this->display_view('users/register');
            }
        } else {
            $this->display_view('users/register');
        }
    }

    function is_correct_captcha($captcha) {
        $expiration = time() - 1800;
        $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
        $binds = array($captcha, $this->input->ip_address(), $expiration);
        $query = $this->db->query($sql, $binds);
        $row = $query->row();

        if ($row->count == 0) {
            $this->form_validation->set_message('is_correct_captcha', 'Please enter correct word in the picture!');
            return FALSE;
        }
        return TRUE;
    }

    public function _active_check($email) {
        if ($this->User_m->active_check($email)) {
            $this->form_validation->set_message('_active_check', $this->lang->line('banned'));
            return FALSE;
        } else {
            return TRUE;
        }
    }

    public function _email_check($email) {
        if ($this->User_m->email_check($email)) {
            $this->form_validation->set_message('_email_check', $this->lang->line('user_error_email'));
            return FALSE;
        } else {
            return TRUE;
        }
    }

    public function success() {
        $this->_data['hmenu_index'] = 0;
        $this->display_view('users/success');
    }

    public function active_user($user_id) {
        $this->_data['hmenu_index'] = 0;
        if ($this->User_m->active_user($user_id) > 0) {
            $this->session->set_flashdata('success', lang('register') . ' ' . lang('success') . ' ' . lang('confirm'));
        } else {
            $this->session->set_flashdata('error', lang('confirm1'));
        }

        redirect('user/success');
    }

    public function forgot_pass() {
        $this->_data['hmenu_index'] = 0;
        $config = array(
        array(
        'field' => 'forgot_email',
        'label' => 'email',
        'rules' => 'required|valid_email'
        )
        );
        $this->form_validation->set_rules($config);
        $config['charset'] = 'utf-8';
        $config['wordwrap'] = TRUE;
        $config['mailtype'] = 'html';

        $this->email->initialize($config);
        if ($this->input->post('submit')) {
            if ($this->form_validation->run()) {
                $temp_pass = random_string('alnum', 16);
                $email = $this->input->post('forgot_email');

                $account_info = $this->User_m->get_account_infor_by_email($email);
                if ($account_info->num_rows() > 0) {
                    $account = $account_info->row();
                    $data = array(
                    'password' => md5($temp_pass)
                    );
                    if ($this->User_m->update_temp_pass($email, $data) > 0) {
                        $this->email->from('dungkirimi@gmail.com', 'Bellizeno');
                        $this->email->to($email);
                        $this->email->subject(lang('forgot_pass'));
                        $message = lang('hello') . $account->display_name . lang('note_forgot_pass') . $account->email . lang('note_forgot_pass1') . $temp_pass . '</p>';
                        $this->email->message($message);
                        if ($this->email->send()) {
                            $this->session->set_flashdata('error', lang('send_mail_success'));
                            redirect('user/forgot_pass');
                        } else {
                            $this->session->set_flashdata('error', lang('send_mail_error'));
                            redirect('user/forgot_pass');
                        }
                    }
                } else {
                    $this->session->set_flashdata('error', lang('invalid_email'));
                    redirect('user/forgot_pass');
                }
            } else {
                $this->display_view('users/forgot_pass');
            }
        } else {
            $this->display_view('users/forgot_pass');
        }
    }

    public function edit_profile($id='') {
        is_user();
        $this->_data['hmenu_index'] = 0;
        $this->session->set_userdata('current_url', current_url());
        $this->_data['query'] = $this->Admin_user_m->get_user_by_id($id);
        $this->_data['addresses'] = $this->Admin_user_m->get_address_by_user_id($id);
        if ($this->input->post('submit')) {
            $birthday = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . '06:00';
            $dob_long = human_to_unix($birthday);
            $config = array(
            array(
            'field' => 'first_name',
            'label' => lang('first_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'last_name',
            'label' => lang('last_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'email',
            'label' => lang('email'),
            'rules' => 'required|valid_email'
            ),
            array(
            'field' => 'display_name',
            'label' => lang('display_name'),
            'rules' => 'required'
            )
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run()) {
                $image_path = './assets/users';
                $thumb_path = $image_path . '/images';
                $config = array(
                'allowed_types' => "jpg|jpeg|gif|png",
                'upload_path' => $image_path,
                'max_size' => 10000,
                'encrypt_name' => TRUE
                );
                $this->load->library('upload', $config);
                if ($this->upload->do_upload()) {
                    //delete old image
                    $file_name = './assets/users/images/' . $user['gravatar'];
                    if ($user['gravatar'] != null) {
                        delete_my_file($file_name);
                    }

                    $upload_info = $this->upload->data();
                    $config = array(
                    'source_image' => $upload_info['full_path'], //get original image
                    'new_image' => $thumb_path, //save as new image //need to create thumbs first
                    'maintain_ratio' => true,
                    'width' => 300,
                    'height' => 200
                    );
                    $this->load->library('image_lib', $config); //load library
                    $this->image_lib->resize(); //do whatever specified in config
                    delete_my_file($upload_info['full_path']);

                    $data_user = array(
                    'last_login' => time(),
                    'active' => 1,
                    'group_id' => 3
                    );
                    $data_profile = array(
                    'display_name' => $this->input->post('display_name'),
                    'first_name' => $this->input->post('first_name'),
                    'last_name' => $this->input->post('last_name'),
                    'gender' => $this->input->post('gender'),
                    'dob' => $dob_long,
                    'phone' => $this->input->post('phone'),
                    'mobile' => $this->input->post('mobile'),
                    'gravatar' => $upload_info['file_name']
                    );
                    $this->Admin_user_m->edit_profile($id, $data_user, $data_profile);
                    $this->session->set_userdata('client_display_name', $this->input->post('display_name'));
                    redirect(current_url());
                } else {
                    $data_user = array(
                    'last_login' => time(),
                    'active' => 1,
                    'group_id' => 3
                    );
                    $data_profile = array(
                    'display_name' => $this->input->post('display_name'),
                    'first_name' => $this->input->post('first_name'),
                    'last_name' => $this->input->post('last_name'),
                    'gender' => $this->input->post('gender'),
                    'dob' => $dob_long,
                    'phone' => $this->input->post('phone'),
                    'mobile' => $this->input->post('mobile')
                    );
                    $this->Admin_user_m->edit_profile($id, $data_user, $data_profile);
                    $this->session->set_userdata('client_display_name',$this->input->post('display_name'));
                    redirect(current_url());
                }
            } else {
                $this->display_view('users/edit_user');
            }
        } else {
            $this->display_view('users/edit_user');
        }
    }

    public function change_pass($user_id) {
        is_user();
        $this->_data['hmenu_index'] = 0;
        $this->session->set_userdata('current_url', current_url());
        $config = array(
        array(
        'field' => 'apass',
        'label' => lang('old_pass'),
        'rules' => 'required|md5'
        ),
        array(
        'field' => 'npass',
        'label' => lang('new_pass'),
        'rules' => 'required|matches[confirm_npass]|md5'
        ),
        array(
        'field' => 'confirm_npass',
        'label' => lang('conf_pass'),
        'rules' => 'required|md5'
        )
        );
        $this->form_validation->set_rules($config);
        if ($this->form_validation->run()) {
            $pass = $this->input->post('apass');
            $query = $this->Admin_m->is_password($pass, $user_id);
            if ($query) {
                $npass = $this->input->post('npass');
                $query1 = $this->Admin_m->change_pass($user_id, $npass);
                if ($query) {
                    $this->session->set_flashdata('error', lang('change_pass') . lang('success'));
                } else {
                    $this->session->set_flashdata('error', lang('change_pass') . lang('fail'));
                }
                redirect('home');
            } else {
                $this->session->set_flashdata('error', lang('in_pass'));
                redirect('user/change_pass' . '/' . $user_id);
            }
        }else
            $this->display_view('users/change_pass');
    }
    function edit_address($id_address){
        $this->_data['hmenu_index'] = 0;
        $this->session->set_userdata('current_url', current_url());
        $this->_data['address'] = $this->User_m->get_address_by_id($id_address);
        if($this->input->post('edit_address')){
            $config = array(
            array(
            'field' => 'first_name',
            'label' => lang('first_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'last_name',
            'label' => lang('last_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'address',
            'label' => lang('address'),
            'rules' => 'required'
            ),
            array(
            'field' => 'phone_mobile',
            'label' => lang('mobile'),
            'rules' => 'required|min_length[10]'
            ),
            array(
            'field' => 'phone',
            'label' => lang('phone'),
            'rules' => 'min_length[10]'
            )
            );
            $this->form_validation->set_rules($config);
            if($this->form_validation->run()){
                if($this->User_m->edit_address($_POST,$id_address)>0){
                    redirect('user/edit_profile/'.$this->session->userdata('client_id'));
                }
                redirect(current_url());    
            } else{
                $this->display_view('users/edit_address');    
            }
        } else{
            $this->display_view('users/edit_address');
        }
    }
    function delete_address(){
        $id_address = $this->input->post('id_address');
        if($this->User_m->delete_address($id_address)>0){
            echo 1;
        } else{
            echo 0;
        }
    }
    function add_address(){
        $this->_data['hmenu_index'] = 0;
        $this->session->set_userdata('current_url', current_url());
        $back = $this->input->post('back');
        $this->_data['back'] = $back;
        if($this->input->post('add_address')){
            $config = array(
            array(
            'field' => 'first_name',
            'label' => lang('first_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'last_name',
            'label' => lang('last_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'address',
            'label' => lang('address'),
            'rules' => 'required'
            ),
            array(
            'field' => 'phone_mobile',
            'label' => lang('mobile'),
            'rules' => 'required|min_length[10]'
            ),
            array(
            'field' => 'phone',
            'label' => lang('phone'),
            'rules' => 'min_length[10]'
            )
            );
            $this->form_validation->set_rules($config);
            if($this->form_validation->run()){
                $this->User_m->add_address($_POST);
                if($back!=''){
                    redirect($this->_data['back']);
                }
                redirect('user/edit_profile/'.$this->session->userdata('client_id'));    
            } else{
                $this->display_view('users/add_address');
            }    
        } else{
            $this->display_view('users/add_address');
        }
    }
    function get_address(){
        $id_address = $this->input->post('id_address');
        $address = $this->User_m->get_address_by_id($id_address);
        $address_data = array();
        $address_data['first_name'] = $address->first_name;
        $address_data['last_name'] = $address->last_name;
        $address_data['company'] = $address->company;
        $address_data['address'] = $address->address;
        $address_data['phone_mobile'] = $address->phone_mobile;
        $address_data['phone'] = $address->phone;
        echo json_encode($address_data);
    }
    function address_ajax_edit(){
        $id_address = $this->input->post('id_address');
        $address_data = array();
        $address_data['first_name'] = $this->input->post('first_name');
        $address_data['last_name'] = $this->input->post('last_name');
        $address_data['company'] = $this->input->post('company');
        $address_data['address'] = $this->input->post('address');
        $address_data['phone_mobile'] = $this->input->post('mobile');
        $address_data['phone'] = $this->input->post('phone');
          echo $this->User_m->edit_address_order($address_data,$id_address);
    }
}
